package cn.project.engineering.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.text.format.DateFormat
import android.text.format.DateUtils
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import cn.project.engineering.R
import cn.project.engineering.base.MyAppCompatActivity
import cn.project.engineering.http.HttpClient
import cn.project.engineering.http.RequestCallback
import cn.project.engineering.http.bean.*
import cn.project.engineering.ui.adapter.MenuAdapter
import cn.project.engineering.ui.view.WonderfulDialog
import cn.project.engineering.utils.DialogCallback
import cn.project.engineering.utils.IpAddressUtils
import cn.project.engineering.utils.toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.xuexiang.xui.widget.textview.MarqueeTextView
import com.xuexiang.xui.widget.textview.marqueen.DisplayEntity
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.android.synthetic.main.activity_main.*
import log.KLog

/**
 *
 * @author  lifuhai
 * @date 2021/2/19 16:43
 */
class MainActivity : MyAppCompatActivity() {

    companion object {
        private const val TAG = "MainActivity"
        private const val FACTORY_INFO_DATE = "factoryInfoData"

        /**
         * 刷新数据间隔时间 15s
         */
        private const val DATA_REFRESH_TIME = 15 * DateUtils.SECOND_IN_MILLIS

        fun start(context: Context, factoryInfo: FactoryInfo?) {
            val intent = Intent(context, MainActivity::class.java)
            factoryInfo?.let {
                intent.putExtra(FACTORY_INFO_DATE, it)
            }

            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            context.startActivity(intent)
        }
    }

    private var factoryInfo: FactoryInfo? = null
    private var isStop = false
    private var orientationUtils: OrientationUtils? = null
    private val macAddress = IpAddressUtils.getMacAddress()
    private val handler = Handler(Looper.getMainLooper())
    private  var ishow:Boolean=false

    /**
     * 当前正在播放的视频地址
     */
    private var currentVideoUrl = ""

    /**
     * 当前图片播放的url
     */
    private var currentImageUrl = ""

   /**
     * 当前banner state
     */
    private var currentBannerState= ""


    /**
     * 跑马灯文字
     */
    private var  strNotice = ""

    /**
     * 数据刷新线程
     */
    private val refreshDataRunnable = object : Runnable {
        override fun run() {
            initMenu()
            initBanner()
            initVideo()
            checkEsop()
            initNotice()
            // 15s后刷新数据
            handler.postDelayed(this, DATA_REFRESH_TIME)
        }
    }
    /**
     * 时间刷新线程
     */
    private val refreshTimeRunnable = object : Runnable {
        override fun run() {
            //
            val currentTimeMillis = System.currentTimeMillis();
            var time=DateFormat.format("yyyy-MM-dd HH:mm:ss",currentTimeMillis)
            currenet_time.setText(""+time)
            handler.postDelayed(this, 1000)
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        orientationUtils = OrientationUtils(this, videoPlayer)
        factoryInfo = intent.getSerializableExtra(FACTORY_INFO_DATE) as? FactoryInfo
        factoryInfo?.let {
            // 已获取过数据直接展示公告
            showNotice()
        } ?: initNotice()
        initView()
        initMenu()
        initBanner()
        initVideo()
        checkEsop()
        // 15s后刷新数据
        handler.postDelayed(refreshDataRunnable, DATA_REFRESH_TIME)
        handler.postDelayed(refreshTimeRunnable,1000)
    }

    override fun netWork(isnet: Boolean) {
    }

    private fun initView() {
        flabel_flabel.setOnKeyListener { v, keyCode, event ->
            when(keyCode) {
                KeyEvent.KEYCODE_ENTER -> {
                    // 回车
                    HttpClient.httpService().saveFlable(MacIP = macAddress, WOID = woid_flabel.text.toString().trim(), FLabel = flabel_flabel.text.toString().trim()).enqueue(object : RequestCallback<String> {
                        override fun onRequestSuccess(body: String?) {
                            body?.let {
                                if (it.isNotEmpty()) {
                                    toast(body)
                                    KLog.d(TAG, "-----：" + it)
                                    flabel_flabel.setText("")

                                }
                            }
                        }

                        override fun onRequestFail(error: RequestError) {
                            KLog.d(TAG, "提空标签扫描出错：${error.message}")
                        }
                    })
                }
            }
            false
        }

        btnVideo.setOnClickListener {
            videoPlayer.visibility = View.VISIBLE
            videoPlayer.startPlayLogic()
        }
        btnBack.setOnClickListener {
            prePage()
        }
        btnNext.setOnClickListener {
            nextPage()
        }
        btnStop.setOnClickListener {
            playVideo()
        }
        kaiguan_munu.setOnClickListener{
            ishow=!ishow;
            if (ishow){
                drawer_layout_home.openDrawer(Gravity.LEFT);
            }else{
                drawer_layout_home.closeDrawer(Gravity.LEFT)
            }

        }
    }

    /**
     * 上一页
     */
    private fun prePage() {
        if (0 == banner.currentItem) {
            toast("已经是第一张了!")
            return
        }

        banner.currentItem = banner.currentItem - 1
    }

    /**
     * 下一页
     */
    private fun nextPage() {
        if (banner.currentItem == banner.itemCount) {
            toast("已经是最后一张了！")
            return
        }

        banner.currentItem = banner.currentItem + 1
    }

    /**
     * 视频播放、暂停操作
     */
    private fun playVideo() {
        when (isStop) {
            true -> {
                toast("已播放！")
                isStop = false
                banner.start()
                btnStop.text = "暂停"
            }
            false -> {
                toast("已暂停！")
                isStop = true;
                banner.stop();
                btnStop.text = "播放"
            }
        }
    }

    /**
     * 初始化公告信息
     */
    private fun initNotice() {
        HttpClient.httpService().getFactoryInfo(MacIP = IpAddressUtils.getMacAddress()).enqueue(object : RequestCallback<List<FactoryInfo>> {
            override fun onRequestSuccess(body: List<FactoryInfo>?) {
                body?.let {
                    if (it.isNotEmpty()) {
                        tvNotice.setOnMarqueeListener(object : MarqueeTextView.OnMarqueeListener {
                            override fun onStartMarquee(displayEntity: DisplayEntity?, index: Int): DisplayEntity? {
                                return displayEntity
                            }

                            override fun onMarqueeFinished(displayDatas: MutableList<DisplayEntity>?): MutableList<DisplayEntity>? {
                                return displayDatas
                            }
                        })
                        factoryInfo= it[0]
                        if (TextUtils.isEmpty(factoryInfo!!.Notice)){
                            return@let
                        }
                        showNotice()
                    } else {
                        tvNotice.clear()
                    }
                }
            }

            override fun onRequestFail(error: RequestError) {
                KLog.d(TAG, "获取公告信息出错：${error.message}")
            }
        })
    }

    /**
     * 初始化菜单
     */
    private fun initMenu() {
        HttpClient.httpService().getMenuInfo().enqueue(object : RequestCallback<List<MenuInfo>> {
            override fun onRequestSuccess(body: List<MenuInfo>?) {
                body?.let {
                    if (it.isNotEmpty()) {
                        val menuAdapter = MenuAdapter(this@MainActivity)
                        menuAdapter.onVideoClickListener = {
                            videoPlayer.visibility = View.VISIBLE
                            videoPlayer.startPlayLogic()
                        }
                        menuAdapter.Onback={
                            WonderfulDialog.passDialog(this@MainActivity,object :DialogCallback{
                                override fun confirm(value: String) {
                                    getPass(value,true)
                                }

                                override fun cancel() {

                                }
                            },"")

                        }
                        menuAdapter.flable={
                            if (flabel_body.visibility==8){
                                HttpClient.httpService().searchFlable().enqueue(object :RequestCallback<List<FlabelInfo>>{
                                    override fun onRequestSuccess(body: List<FlabelInfo>?) {
                                        body?.let {
                                            if (it.isNotEmpty()) {
                                                val flabelInfo = body[0];
                                                woid_flabel.setText(flabelInfo.WOID)
                                                partno_flabel.setText(flabelInfo.PartNO)
                                                partname_flabel.setText(flabelInfo.PartName)
                                                flabel_body.visibility=View.VISIBLE
                                                flabel_flabel.requestFocus()
                                            }
                                        }

                                    }

                                    override fun onRequestFail(error: RequestError) {
                                        KLog.d(TAG, "获取标签扫描出错：${error.message}")


                                    }
                                })
                            }else{
                                flabel_body.visibility=View.GONE
                                flabel_flabel.clearFocus()
                            }
                        }
                        menuAdapter.setData(it)
                        drawRec.adapter = menuAdapter
                        drawRec.layoutManager = LinearLayoutManager(this@MainActivity)
                    }
                }
            }

            override fun onRequestFail(error: RequestError) {

                val  data=ArrayList<MenuInfo>()
                var menu=MenuInfo()
                menu.MenuName="返回启动页面"
                data.add(menu)
                val menuAdapter = MenuAdapter(this@MainActivity)
                menuAdapter.Onback={
                    WonderfulDialog.passDialog(this@MainActivity,object :DialogCallback{
                        override fun confirm(value: String) {
                            getPass(value,false)
                        }

                        override fun cancel() {

                        }
                    },"")

                }
                menuAdapter.setData(data)
                drawRec.adapter = menuAdapter
                drawRec.layoutManager = LinearLayoutManager(this@MainActivity)

                KLog.d(TAG, "获取菜单信息出错：${error.message}")
            }
        })
    }

    /**
     * 初始化轮播图片
     */
    private fun initBanner() {

        HttpClient.httpService().queryBannerState(MacIP = macAddress).enqueue(object :RequestCallback<List<BannerStateInfo>>{
            override fun onRequestSuccess(body: List<BannerStateInfo>?) {
                body?.let {
                    if (it.isNotEmpty()) {
                        val currentFile = it[0].CurrentFile;
                        if (TextUtils.isEmpty(currentFile)){
                            banner.setDatas(null)
                            return
                        }
                        if (currentBannerState.equals(currentFile)){
                            return
                        }
                        currentBannerState=it[0].CurrentFile
                        HttpClient.httpService().queryBanner(MacIP = macAddress, IsVideo = 0).enqueue(object : RequestCallback<List<BannerInfo>> {
                            override fun onRequestSuccess(body: List<BannerInfo>?) {
                                body?.let {
                                    if (it.isNotEmpty()) {
                                        val banners: MutableList<String> = ArrayList()
                                        for (i in 0 until it.size) {
                                            var bannerInfo = it[i]
                                            if (!TextUtils.isEmpty(bannerInfo.Imgurl)) {

                                                val pages = try {
                                                    bannerInfo.Pages.toInt()
                                                } catch (e: NumberFormatException) {
                                                    1
                                                }
                                                val newPages = bannerInfo.Newpages

                                                if (newPages.isEmpty()) {
                                                    for (i in 1 until pages) {
                                                        banners.add("${bannerInfo.Imgurl}$${i}.png")
                                                    }
                                                } else {
                                                    val newPagesSplit = newPages.split(",")

                                                    for (i in newPagesSplit) {
                                                        banners.add("${bannerInfo.Imgurl}$${i}.png")
                                                    }
                                                }
                                            }

                                            banner.setLoopTime(30000)
                                            banner.adapter = object : BannerImageAdapter<String>(banners) {
                                                override fun onBindView(holder: BannerImageHolder, data: String?, position: Int, size: Int) {
                                                    holder.imageView.setOnClickListener(View.OnClickListener { BigPictureActivity.start(this@MainActivity, banners.get(position)) })

                                                    Glide.with(this@MainActivity)
                                                            .load(banners[position])
                                                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                                                            .listener(object : RequestListener<Drawable> {
                                                                override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {

                                                                    holder.imageView.setOnClickListener(View.OnClickListener { BigPictureActivity.start(this@MainActivity, banners.get(position)) })
                                                                    return false
                                                                }

                                                                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                                                                    return false
                                                                }

                                                            })
                                                            .into(holder.imageView)
                                                }

                                                override fun onCreateHolder(parent: ViewGroup?, viewType: Int): BannerImageHolder {
                                                    val imageView = ImageView(this@MainActivity)
                                                    // 注意，必须设置为match_parent，这个是viewpager2强制要求的
                                                    val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                                                    imageView.layoutParams = params
                                                    imageView.scaleType = ImageView.ScaleType.FIT_XY

                                                    return BannerImageHolder(imageView)
                                                }
                                            }


                                        }
                                    }else{
                                        banner.setDatas(null)
                                    }
                                }
                            }

                            override fun onRequestFail(error: RequestError) {
                                KLog.d(TAG, "获取轮播图片信息出错：${error.message}")
                            }
                        })
                    }
                    else
                    {
                        banner.setDatas(null)
                    }
                }


              }

            override fun onRequestFail(error: RequestError) {
                KLog.d(TAG, "获取轮播图片状态信息出错：${error.message}")

            }
        })

    }

    /**
     * 初始化视频信息
     */
    private fun initVideo() {
        HttpClient.httpService().queryBanner(MacIP = macAddress, IsVideo = 1).enqueue(object : RequestCallback<List<BannerInfo>> {
            override fun onRequestSuccess(body: List<BannerInfo>?) {
                body?.let {
                    if (it.isNotEmpty()) {
                        val bannerInfo = it[0]
                        if (TextUtils.isEmpty(currentVideoUrl) || currentVideoUrl != bannerInfo.Imgurl) {
                            // 未播放过视频或返回的视频跟当前正在播放的一不样才去播放视频
                            currentVideoUrl = bannerInfo.Imgurl
                            videoPlayer.setUp(currentVideoUrl, true, "播放视频")
                            videoPlayer.titleTextView.visibility = View.INVISIBLE
                            videoPlayer.isLooping=true
                            videoPlayer.visibility = View.VISIBLE
                            videoPlayer.fullscreenButton.setOnClickListener {
                                videoPlayer.startWindowFullscreen(this@MainActivity, false, true)
                            }
                            videoPlayer.backButton.setOnClickListener {
                                videoPlayer.visibility = View.GONE
                                videoPlayer.onVideoPause()
                            }
                            videoPlayer.setIsTouchWiget(true)
                            videoPlayer.startPlayLogic()
                        }
                    }else{
                        videoPlayer.visibility = View.GONE
                        videoPlayer.onVideoPause()
                        currentVideoUrl=""
                    }
                }
            }

            override fun onRequestFail(error: RequestError) {
                KLog.d(TAG, "获取视频信息出错：${error.message}")
            }
        })
    }



    /**
     * 展示实时消息
     */
    private fun showNotice() {
        factoryInfo?.let {
            if (!TextUtils.isEmpty(it.Notice)) {
                if (it.Notice.equals(strNotice)){
                    return
                }
                val data: MutableList<String> = ArrayList()
                data.add("实时信息：${it.Notice}")
                tvNotice.startSimpleRoll(data)
                strNotice=it.Notice
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        KLog.d(TAG, "-----："+keyCode)
        when (keyCode) {
            KeyEvent.KEYCODE_PAGE_UP -> {
                // 向上
                prePage()
            }
            KeyEvent.KEYCODE_PAGE_DOWN -> {
                // 向下
                nextPage()
            }
            KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
                // 空格键
                playVideo()
            }




        }

        return super.onKeyDown(keyCode, event)
    }
    override fun onResume() {
        super.onResume()
        videoPlayer.onVideoResume()
    }

    override fun onPause() {
        super.onPause()
        videoPlayer.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        tvNotice.clear()
        GSYVideoManager.releaseAllVideos()
        orientationUtils?.releaseListener()
        handler.removeCallbacks(refreshDataRunnable)
    }

    fun  checkEsop(){
        HttpClient.httpService().checkSop(MacIP = macAddress).enqueue(object : RequestCallback<List<SopInfo>> {
            override fun onRequestSuccess(body: List<SopInfo>?) {
                body?.let {
                    if (it.isNotEmpty()) {
                        val bannerInfo = it[0]
                        if (bannerInfo.IsUpdateVer==1){
                            //
                            var dialog=WonderfulDialog.sopDialog(this@MainActivity,"");
                            handler.postDelayed(Runnable {
                                dialog.dismiss()
                                SopTijiao()
                            },5000)
                        }

                    }
                }
            }

            override fun onRequestFail(error: RequestError) {
                KLog.d(TAG, "获取视频信息出错：${error.message}")
            }
        })
    }

    fun SopTijiao(){
        HttpClient.httpService().tijiaoSop(MacIP = macAddress).enqueue(object : RequestCallback<String> {
            override fun onRequestSuccess(body: String?) {
                body?.let {
                    if (it.isNotEmpty()) {
                        KLog.d(TAG, "-----："+it)

                    }
                }
            }

            override fun onRequestFail(error: RequestError) {
                KLog.d(TAG, "获取视频信息出错：${error.message}")
            }
        })
    }
}